package com.hyperplan.neptune.parser;

import java.util.ArrayList;
import java.util.List;

import com.hyperplan.neptune.lexer.Token;

public abstract class ChoiceParser<T> implements Parser<T> {

	private List<Parser<T>> parsers;
	
	public ChoiceParser() {
		parsers = new ArrayList<Parser<T>>();
	}
	
	public void add(Parser<? extends T> parser) {
		parsers.add(new ConverterParser<T>(parser));
	}
	
	public ParserSolution<T> parse(List<Token> tokens, int index)
			throws ParserException {
		assert !parsers.isEmpty();
		ParserException candidate = null;
		for (Parser<T> parser : parsers) {
			try {
				return parser.parse(tokens, index);
			}
			catch (ParserException exception) {
				if (candidate == null) {
					candidate = exception;
				} else if (exception.getToken().getLocation().compareTo(
						candidate.getToken().getLocation()) > 0) {
					candidate = exception;
				}
			}
		}
		throw candidate;
	}
}
